﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace RM.Weighing
{

    public class Tools
    {
        private const string Key = "ZZrm86650880";

        /// <summary>
        /// 获取机器码
        /// </summary>
        /// <returns>机器码</returns>
        public string ObtainMachineCode()
        {
            string CpuID = Encryptions.DESEncrypt(GetSystemInfo.GetCpuID(), Key);
            string MotherBoardID = Encryptions.DESEncrypt(GetSystemInfo.GetMotherBoardID(), Key);
            string DiskID = Encryptions.DESEncrypt(GetSystemInfo.GetDiskID(), Key);
            return GetNum(CpuID, 8) + GetNum(DiskID, 8) + (MotherBoardID);
        }

        /// <summary>
        /// 获取注册码
        /// </summary>
        /// <param name="RegistrationCode"></param>
        /// <returns></returns>
        public string GetRegistrationCode(string RegistrationCode)
        {
            return Encryptions.GetMD5X2(RegistrationCode);
        }

        /// <summary>
        /// 取数字
        /// </summary>
        /// <param name="md5"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string GetNum(string md5, int len)
        {
            Regex regex = new Regex(@"\d");
            MatchCollection listMatch = regex.Matches(md5);
            string str = "";
            for (int i = 0; i < len; i++)
            {
                str += listMatch[i].Value;
            }
            while (str.Length < len)
            {
                //不足补0
                str += "0";
            }
            return str;

        }



        public class GetSystemInfo
        {
            /// <summary>  
            /// 操作系统的登录用户名  
            /// </summary>  
            /// <returns>系统的登录用户名</returns>  
            public static string GetUserName()
            {
                try
                {
                    string strUserName = string.Empty;
                    ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject mo in moc.Cast<ManagementObject>())
                    {
                        strUserName = mo["UserName"].ToString();
                    }
                    moc = null;
                    mc = null;
                    return strUserName;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取本机MAC地址  
            /// </summary>  
            /// <returns>本机MAC地址</returns>  
            public static string GetMacAddress()
            {
                try
                {
                    string strMac = string.Empty;
                    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject mo in moc)
                    {
                        if ((bool)mo["IPEnabled"] == true)
                        {
                            strMac = mo["MacAddress"].ToString();
                        }
                    }
                    moc = null;
                    mc = null;
                    return strMac;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取本机的物理地址  
            /// </summary>  
            /// <returns></returns>  
            public static string getMacAddr_Local()
            {
                string madAddr = null;
                try
                {
                    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection moc2 = mc.GetInstances();
                    foreach (ManagementObject mo in moc2)
                    {
                        if (Convert.ToBoolean(mo["IPEnabled"]) == true)
                        {
                            madAddr = mo["MacAddress"].ToString();
                            madAddr = madAddr.Replace(':', '-');
                        }
                        mo.Dispose();
                    }
                    if (madAddr == null)
                    {
                        return "unknown";
                    }
                    else
                    {
                        return madAddr;
                    }
                }
                catch (Exception)
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取客户端内网IPv6地址  
            /// </summary>  
            /// <returns>客户端内网IPv6地址</returns>  
            public static string GetClientLocalIPv6Address()
            {
                string strLocalIP = string.Empty;
                try
                {
                    IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
                    IPAddress ipAddress = ipHost.AddressList[0];
                    strLocalIP = ipAddress.ToString();
                    return strLocalIP;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取客户端内网IPv4地址  
            /// </summary>  
            /// <returns>客户端内网IPv4地址</returns>  
            public static string GetClientLocalIPv4Address()
            {
                List<string> list = GetLocalIpAddress("InterNetwork");
                if (list != null)
                {
                    return list[0];
                }
                else
                {
                    return null;
                }
            }

            /// <summary>
            /// 获取本机所有ip地址
            /// </summary>
            /// <param name="netType">"InterNetwork":ipv4地址，"InterNetworkV6":ipv6地址</param>
            /// <returns>ip地址集合</returns>
            private static List<string> GetLocalIpAddress(string netType)
            {
                string hostName = Dns.GetHostName();                    //获取主机名称  
                IPAddress[] addresses = Dns.GetHostAddresses(hostName); //解析主机IP地址  

                List<string> IPList = new List<string>();
                if (netType == string.Empty)
                {
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        IPList.Add(addresses[i].ToString());
                    }
                }
                else
                {
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        if (addresses[i].AddressFamily.ToString() == netType)
                        {
                            IPList.Add(addresses[i].ToString());
                        }
                    }
                }
                return IPList;
            }

            /// <summary>  
            /// 获取客户端内网IPv4地址集合  
            /// </summary>  
            /// <returns>返回客户端内网IPv4地址集合</returns>  
            public static List<string> GetClientLocalIPv4AddressList()
            {
                List<string> ipAddressList = new List<string>();
                try
                {
                    IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
                    foreach (IPAddress ipAddress in ipHost.AddressList)
                    {
                        if (!ipAddressList.Contains(ipAddress.ToString()))
                        {
                            ipAddressList.Add(ipAddress.ToString());
                        }
                    }
                }
                catch
                {

                }
                return ipAddressList;
            }

            /// <summary>  
            /// 获取客户端外网IP地址  
            /// </summary>  
            /// <returns>客户端外网IP地址</returns>  
            public static string GetClientInternetIPAddress()
            {
                string strInternetIPAddress = string.Empty;
                try
                {
                    using (WebClient webClient = new WebClient())
                    {
                        strInternetIPAddress = webClient.DownloadString("http://www.coridc.com/ip");
                        Regex r = new Regex("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
                        System.Text.RegularExpressions.Match mth = r.Match(strInternetIPAddress);
                        if (!mth.Success)
                        {
                            strInternetIPAddress = GetClientInternetIPAddress2();
                            mth = r.Match(strInternetIPAddress);
                            if (!mth.Success)
                            {
                                strInternetIPAddress = "unknown";
                            }
                        }
                        return strInternetIPAddress;
                    }
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取本机公网IP地址  
            /// </summary>  
            /// <returns>本机公网IP地址</returns>  
            private static string GetClientInternetIPAddress2()
            {
                string tempip = "";
                try
                {
                    //http://iframe.ip138.com/ic.asp 返回的是：您的IP是：[220.231.17.99] 来自：北京市 光环新网  
                    WebRequest wr = WebRequest.Create("http://iframe.ip138.com/ic.asp");
                    Stream s = wr.GetResponse().GetResponseStream();
                    StreamReader sr = new StreamReader(s, Encoding.Default);
                    string all = sr.ReadToEnd(); //读取网站的数据  

                    int start = all.IndexOf("[") + 1;
                    int end = all.IndexOf("]", start);
                    tempip = all.Substring(start, end - start);
                    sr.Close();
                    s.Close();
                    return tempip;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取硬盘序号  
            /// </summary>  
            /// <returns>硬盘序号</returns>  
            public static string GetDiskID()
            {
                try
                {
                    string strDiskID = string.Empty;
                    ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject mo in moc)
                    {
                        strDiskID = mo.Properties["Model"].Value.ToString();
                    }
                    moc = null;
                    mc = null;
                    return strDiskID;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取CpuID  
            /// </summary>  
            /// <returns>CpuID</returns>  
            public static string GetCpuID()
            {
                try
                {
                    string strCpuID = string.Empty;
                    ManagementClass mc = new ManagementClass("Win32_Processor");
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject mo in moc)
                    {
                        strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                    }
                    moc = null;
                    mc = null;
                    return strCpuID;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取操作系统类型  
            /// </summary>  
            /// <returns>操作系统类型</returns>  
            public static string GetSystemType()
            {
                try
                {
                    string strSystemType = string.Empty;
                    ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject mo in moc)
                    {
                        strSystemType = mo["SystemType"].ToString();
                    }
                    moc = null;
                    mc = null;
                    return strSystemType;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取操作系统名称  
            /// </summary>  
            /// <returns>操作系统名称</returns>  
            public static string GetSystemName()
            {
                try
                {
                    string strSystemName = string.Empty;
                    ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT PartComponent FROM Win32_SystemOperatingSystem");
                    foreach (ManagementObject mo in mos.Get())
                    {
                        strSystemName = mo["PartComponent"].ToString();
                    }
                    mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT Caption FROM Win32_OperatingSystem");
                    foreach (ManagementObject mo in mos.Get())
                    {
                        strSystemName = mo["Caption"].ToString();
                    }
                    return strSystemName;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取物理内存信息  
            /// </summary>  
            /// <returns>物理内存信息</returns>  
            public static string GetTotalPhysicalMemory()
            {
                try
                {
                    string strTotalPhysicalMemory = string.Empty;
                    ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                    ManagementObjectCollection moc = mc.GetInstances();
                    foreach (ManagementObject mo in moc)
                    {
                        strTotalPhysicalMemory = mo["TotalPhysicalMemory"].ToString();
                    }
                    moc = null;
                    mc = null;
                    return strTotalPhysicalMemory;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>  
            /// 获取主板id  
            /// </summary>  
            /// <returns></returns>  
            public static string GetMotherBoardID()
            {
                try
                {
                    ManagementClass mc = new ManagementClass("Win32_BaseBoard");
                    ManagementObjectCollection moc = mc.GetInstances();
                    string strID = null;
                    foreach (ManagementObject mo in moc)
                    {
                        strID = mo.Properties["SerialNumber"].Value.ToString();
                        break;
                    }
                    return strID;
                }
                catch
                {
                    return "unknown";
                }
            }

            /// <summary>
            /// 获取公用桌面路径 
            /// </summary>
            /// <returns></returns>
            public static string GetAllUsersDesktopFolderPath()
            {
                RegistryKey folders;
                folders = OpenRegistryPath(Registry.LocalMachine, @"/software/microsoft/windows/currentversion/explorer/shell folders");
                string desktopPath = folders.GetValue("Common Desktop").ToString();
                return desktopPath;
            }

            /// <summary>  
            /// 获取公用启动项路径  
            /// </summary>  
            public static string GetAllUsersStartupFolderPath()
            {
                RegistryKey folders;
                folders = OpenRegistryPath(Registry.LocalMachine, @"/software/microsoft/windows/currentversion/explorer/shell folders");
                string Startup = folders.GetValue("Common Startup").ToString();
                return Startup;
            }

            /// <summary>
            /// 打开注册表路径
            /// </summary>
            /// <param name="root">注册表项</param>
            /// <param name="s"></param>
            /// <returns></returns>
            private static RegistryKey OpenRegistryPath(RegistryKey root, string s)
            {
                s = s.Remove(0, 1) + @"/";
                while (s.IndexOf(@"/") != -1)
                {
                    root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"/")));
                    s = s.Remove(0, s.IndexOf(@"/") + 1);
                }
                return root;
            }

            public static object GetRegistData(string RegistName)
            {
                string[] subkeyname;
                bool yesofno = false;
                RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
                subkeyname = key.GetSubKeyNames();
                foreach (string subkey in subkeyname)
                {
                    if (subkey.Equals(RegistName))
                    {
                        yesofno = true;
                        break;
                    }
                }

                if (yesofno)
                {
                    string aa = $"{RegistName}\\registryData";
                    RegistryKey registryKey = key.OpenSubKey(aa, true);
                    var a = registryKey.GetValueNames();
                    var b = registryKey.GetValue(a[0]).ToString();
                    return b;

                }
                else
                {
                    string aa = $"{RegistName}\\registryData";
                    RegistryKey datakey = key.CreateSubKey(aa, true);
                    datakey.SetValue("data", "0123456789");
                    return null;
                }

            }

            public static void SetRegistData(string RegistName, string RegistData)
            {
                RegistryKey Key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
                string a = $"{RegistName}\\registryData";
                RegistryKey registryKey = Key.OpenSubKey(a, true);
                try
                {
                    registryKey.SetValue("data", RegistData);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    throw;
                }
            }


        }


        /// <summary>
        /// 加密解密的工具类
        /// </summary>
        public static class Encryptions
        {
            public static byte[] GetBytes(string text, int length)
            {
                if (text.Length < length)
                {
                    int length1 = text.Length;
                    for (int i = 0; i < length - length1; i++)
                    {
                        text = "0" + text;
                    }
                }

                byte[] bytes = Encoding.UTF8.GetBytes(text);
                return bytes;
            }

            /// <summary>
            /// 获取MD5值
            /// </summary>
            /// <param name="inputStr">指定字符串</param>
            /// <returns>返回MD5X值</returns>
            public static string GetMD5X(string inputStr)
            {
                //创建MD5对象
                MD5 md5 = MD5.Create();
                //先将字符串转换成字节数组
                byte[] buffer = Encoding.Default.GetBytes(inputStr);
                byte[] Md5Buffer = md5.ComputeHash(buffer);
                //将字节数组转换成字符串
                string str = "";
                for (int i = 0; i < Md5Buffer.Length; i++)
                {
                    str += Md5Buffer[i].ToString("x");
                }
                return str;
            }
            /// <summary>
            /// 获取MD5值
            /// </summary>
            /// <param name="inputStr">指定字符串</param>
            /// <returns>返回对齐的MD5值</returns>
            public static string GetMD5X2(string inputStr)
            {
                //创建MD5对象
                MD5 md5 = MD5.Create();
                //先将字符串转换成字节数组
                byte[] buffer = Encoding.Default.GetBytes(inputStr);
                byte[] Md5Buffer = md5.ComputeHash(buffer);
                //将字节数组转换成字符串
                string str = "";
                for (int i = 0; i < Md5Buffer.Length; i++)
                {
                    str += Md5Buffer[i].ToString("x2");
                }
                return str;
            }

            /// <summary>
            /// DES加密
            /// </summary>
            /// <param name="str">需要加密的</param>
            /// <param name="sKey">密匙</param>
            /// <returns></returns>
            public static string DESEncrypt(string str, string sKey)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray;
                inputByteArray = Encoding.Default.GetBytes(str);
                des.Key = Encoding.ASCII.GetBytes(GetMd5Hash(sKey).Substring(0, 8));
                des.IV = Encoding.ASCII.GetBytes(GetMd5Hash(sKey).Substring(0, 8));
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                return ret.ToString();
            }

            /// <summary>
            /// DES解密
            /// </summary>
            /// <param name="pToDecrypt">需要解密的</param>
            /// <param name="sKey">密匙</param>
            /// <returns></returns>
            public static string DESDecrypt(string pToDecrypt, string sKey)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                int len;
                len = pToDecrypt.Length / 2;
                byte[] inputByteArray = new byte[len];
                int x, i;
                for (x = 0; x < len; x++)
                {
                    i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }
                des.Key = Encoding.ASCII.GetBytes(GetMd5Hash(sKey).Substring(0, 8));
                des.IV = Encoding.ASCII.GetBytes(GetMd5Hash(sKey).Substring(0, 8));
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.Default.GetString(ms.ToArray());
            }
            public static string GetMd5Hash(string input)
            {
                MD5 md5Hash = MD5.Create();

                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                // Create a new Stringbuilder to collect the bytes
                // and create a string.
                StringBuilder sBuilder = new StringBuilder();

                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
                // Return the hexadecimal string.
                return sBuilder.ToString();
            }
        }
    }
}
